<template>
	<div class="app-container">
		<!-- 查询区域 -->
		<el-card class="search-card">
			<el-form :model="queryParams">
				<el-row :gutter="20">
					<el-col :span="5">
						<el-form-item label="报告编号">
							<el-input
								v-model="queryParams.reportNumber"
								placeholder="请输入报告编号"
								clearable
								@keyup.enter="handleQuery"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="5">
						<el-form-item label="盘点日期">
							<el-date-picker
								v-model="queryParams.inventoryDate"
								type="date"
								placeholder="选择盘点日期"
								value-format="YYYY-MM-DD"
								style="width: 100%"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="5">
						<el-form-item label="关联计划">
							<el-select
								v-model="queryParams.planId"
								placeholder="请选择关联计划"
								clearable
								filterable
							>
								<el-option
									v-for="item in planOptions"
									:key="item.id"
									:label="item.name"
									:value="item.id"
								/>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="5">
						<el-form-item label="状态">
							<el-select
								v-model="queryParams.status"
								placeholder="请选择状态"
								clearable
							>
								<el-option label="待审核" :value="0" />
								<el-option label="已审核" :value="1" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="4" style="text-align: left">
						<el-button type="primary" @click="handleQuery">查询</el-button>
						<el-button @click="resetQuery">重置</el-button>
					</el-col>
				</el-row>
			</el-form>
		</el-card>

		<!-- 数据表格区域 -->
		<el-card class="mt-1">
			<el-button type="primary" @click="handleAdd">
				<el-icon>
					<Plus />
				</el-icon>
				新增报告
			</el-button>
			<el-button type="primary" @click="handleExport">
				<el-icon>
					<Download />
				</el-icon>
				导出报告
			</el-button>
			<el-table
				:data="reportList"
				border
				v-loading="loading"
				@selection-change="handleSelectionChange"
				class="mt-2"
			>
				<el-table-column type="selection" align="center" />
				<el-table-column prop="reportNumber" label="报告编号" align="center" />
				<el-table-column prop="inventoryDate" label="盘点日期" align="center" />
				<el-table-column prop="planId" label="关联计划" align="center">
					<template #default="{ row }">
						<el-tag>{{
							getName(planOptions, row.planId, "id", "name")
						}}</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="staff" label="盘点人员" align="center" />
				<el-table-column label="设备差异" align="center">
					<template #default="{ row }">
						<span style="color: green">+{{ row.deviceProfitCount }}</span> /
						<span style="color: red">-{{ row.deviceLossCount }}</span>
					</template>
				</el-table-column>
				<el-table-column label="物料差异" align="center">
					<template #default="{ row }">
						<span style="color: green">+{{ row.materialProfitCount }}</span> /
						<span style="color: red">-{{ row.materialLossCount }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="status" label="状态" align="center">
					<template #default="{ row }">
						<el-tag :type="row.status === 1 ? 'success' : 'warning'">
							{{ row.status === 1 ? "已审核" : "待审核" }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="reviewedAt" label="审核时间" align="center" />
				<el-table-column
					prop="reviewedResult"
					label="审核结果"
					align="center"
				/>
				<el-table-column label="操作" align="center" width="220">
					<template #default="{ row }">
						<el-button size="small" @click="handleView(row)">查看</el-button>
						<el-button
							size="small"
							type="primary"
							@click="handleEdit(row)"
							v-if="row.status === 0"
						>
							编辑
						</el-button>
						<el-button
							size="small"
							type="success"
							@click="handleAudit(row)"
							v-if="row.status === 0"
						>
							审核
						</el-button>
						<el-button size="small" type="danger" @click="handleDelete(row)">
							删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>

			<!-- 分页区域 -->
			<el-pagination
				class="mt-2"
				background
				layout="total, sizes, prev, pager, next, jumper"
				:total="total"
				v-model:page-size="queryParams.pageSize"
				v-model:current-page="queryParams.pageNum"
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
			/>
		</el-card>

		<!-- 新增/编辑对话框 -->
		<el-dialog
			v-model="dialog.visible"
			:title="dialog.title"
			width="800px"
			:close-on-click-modal="false"
		>
			<el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
				<!-- <el-form-item label="报告编号" prop="reportNumber">
          <el-input v-model="form.reportNumber" placeholder="请输入报告编号" />
        </el-form-item> -->
				<el-form-item label="盘点日期" prop="inventoryDate">
					<el-date-picker
						v-model="form.inventoryDate"
						type="date"
						placeholder="选择盘点日期"
						value-format="YYYY-MM-DD"
						style="width: 100%"
					/>
				</el-form-item>
				<el-form-item label="关联计划" prop="planId">
					<el-select
						v-model="form.planId"
						placeholder="请选择关联计划"
						style="width: 100%"
						filterable
					>
						<el-option
							v-for="item in planOptions"
							:key="item.id"
							:label="item.name"
							:value="item.id"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="盘点人员" prop="staff">
					<el-input v-model="form.staff" placeholder="请输入盘点人员" />
				</el-form-item>
				<el-form-item label="设备盘盈数" prop="deviceProfitCount">
					<el-input-number
						v-model="form.deviceProfitCount"
						:min="0"
						controls-position="right"
						style="width: 100%"
					/>
				</el-form-item>
				<el-form-item label="设备盘亏数" prop="deviceLossCount">
					<el-input-number
						v-model="form.deviceLossCount"
						:min="0"
						controls-position="right"
						style="width: 100%"
					/>
				</el-form-item>
				<el-form-item label="物料盘盈数" prop="materialProfitCount">
					<el-input-number
						v-model="form.materialProfitCount"
						:min="0"
						controls-position="right"
						style="width: 100%"
					/>
				</el-form-item>
				<el-form-item label="物料盘亏数" prop="materialLossCount">
					<el-input-number
						v-model="form.materialLossCount"
						:min="0"
						controls-position="right"
						style="width: 100%"
					/>
				</el-form-item>
				<el-form-item label="备注">
					<el-input
						v-model="form.remark"
						type="textarea"
						:rows="3"
						placeholder="请输入备注信息"
					/>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="dialog.visible = false">取消</el-button>
				<el-button type="primary" @click="submitForm">保存</el-button>
			</template>
		</el-dialog>

		<!-- 详情对话框 -->
		<el-dialog
			v-model="detailDialog.visible"
			:title="`盘点报告详情 - ${detailDialog.data.reportNumber}`"
			width="800px"
		>
			<el-descriptions :column="1" border>
				<el-descriptions-item label="报告编号">{{
					detailDialog.data.reportNumber
				}}</el-descriptions-item>
				<el-descriptions-item label="盘点日期">{{
					detailDialog.data.inventoryDate
				}}</el-descriptions-item>
				<el-descriptions-item label="关联计划">{{
					detailDialog.data.planName
				}}</el-descriptions-item>
				<el-descriptions-item label="盘点人员">{{
					detailDialog.data.staff
				}}</el-descriptions-item>
				<el-descriptions-item label="设备盘盈数">
					<span style="color: green">{{
						detailDialog.data.deviceProfitCount
					}}</span>
				</el-descriptions-item>
				<el-descriptions-item label="设备盘亏数">
					<span style="color: red">{{
						detailDialog.data.deviceLossCount
					}}</span>
				</el-descriptions-item>
				<el-descriptions-item label="物料盘盈数">
					<span style="color: green">{{
						detailDialog.data.materialProfitCount
					}}</span>
				</el-descriptions-item>
				<el-descriptions-item label="物料盘亏数">
					<span style="color: red">{{
						detailDialog.data.materialLossCount
					}}</span>
				</el-descriptions-item>
				<el-descriptions-item label="状态">
					<el-tag
						:type="detailDialog.data.status === 1 ? 'success' : 'warning'"
					>
						{{ detailDialog.data.status === 1 ? "已审核" : "待审核" }}
					</el-tag>
				</el-descriptions-item>
				<el-descriptions-item label="审核时间">{{
					detailDialog.data.reviewedAt || "-"
				}}</el-descriptions-item>
				<el-descriptions-item label="审核结果">{{
					detailDialog.data.reviewedResult || "-"
				}}</el-descriptions-item>
				<el-descriptions-item label="创建时间">{{
					detailDialog.data.createTime
				}}</el-descriptions-item>
				<el-descriptions-item label="备注">{{
					detailDialog.data.remark || "无"
				}}</el-descriptions-item>
			</el-descriptions>
			<template #footer>
				<el-button @click="detailDialog.visible = false">关闭</el-button>
			</template>
		</el-dialog>

		<!-- 审核对话框 -->
		<el-dialog
			v-model="auditDialog.visible"
			title="审核盘点报告"
			width="500px"
			:close-on-click-modal="false"
		>
			<el-form
				ref="auditFormRef"
				:model="auditForm"
				:rules="auditRules"
				label-width="120px"
			>
				<el-form-item label="审核结果" prop="auditResult">
					<el-input
						v-model="auditForm.auditResult"
						type="textarea"
						:rows="3"
						placeholder="请输入审核结果描述"
					/>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="auditDialog.visible = false">取消</el-button>
				<el-button type="primary" @click="submitAuditForm">确认审核</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
	import { ref, reactive, onMounted } from "vue";
	import { ElMessage, ElMessageBox } from "element-plus";
	import { Download, Plus } from "@element-plus/icons-vue";
	import {
		getPlanList,
		listInventoryReport,
		getInventoryReportDetail,
		addInventoryReport,
		updateInventoryReport,
		deleteInventoryReport,
		auditInventoryReport,
		exportInventoryReport,
	} from "@/api/prod_operate/device/asset_inventory/inventory_report";

	const handleExport = async () => {
		try {
			// 关键：指定响应类型为blob，确保获取二进制流
			const res = await exportInventoryReport({
				responseType: "blob", // 告知axios以blob类型接收响应
			});

			// 检查响应是否为有效的二进制流（避免后端返回JSON错误）
			if (!res || res.size === 0) {
				ElMessage.error("导出文件为空");
				return;
			}

			// 创建Blob时指定Excel的MIME类型
			const blob = new Blob([res], {
				type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
			});

			// 创建下载链接
			const url = window.URL.createObjectURL(blob);
			const link = document.createElement("a");
			link.href = url;
			link.download = "盘点报告.xlsx"; // 确保扩展名正确
			document.body.appendChild(link);
			link.click();

			// 清理资源
			document.body.removeChild(link);
			window.URL.revokeObjectURL(url); // 释放URL对象，避免内存泄漏

			ElMessage.success("导出成功");
		} catch (error) {
			console.error("导出失败:", error);
			// 处理后端返回的错误信息（若后端在错误时返回JSON）
			try {
				if (error.response?.data) {
					const errorBlob = error.response.data;
					const text = await new Response(errorBlob).text();
					ElMessage.error(`导出失败: ${text || "服务器错误"}`);
				} else {
					ElMessage.error("导出失败，请重试");
				}
			} catch (e) {
				ElMessage.error("导出失败，请重试");
			}
		}
	};
	// 查询参数
	const queryParams = reactive({
		pageNum: 1,
		pageSize: 10,
		reportNumber: "",
		inventoryDate: "",
		planId: undefined,
		status: undefined,
	});

	// 表单数据
	const form = reactive({
		id: undefined,
		reportNumber: "",
		inventoryDate: "",
		planId: undefined,
		staff: "",
		deviceProfitCount: 0,
		deviceLossCount: 0,
		materialProfitCount: 0,
		materialLossCount: 0,
		remark: "",
	});

	// 审核表单
	const auditForm = reactive({
		id: undefined,
		auditResult: "",
	});

	// 对话框控制
	const dialog = reactive({
		visible: false,
		title: "",
	});

	const detailDialog = reactive({
		visible: false,
		data: {},
	});

	const auditDialog = reactive({
		visible: false,
	});

	// 下拉选项数据
	const planOptions = ref([]);

	// 表格数据
	const reportList = ref([]);
	const total = ref(0);
	const loading = ref(false);
	const selectedRows = ref([]);
	const formRef = ref();
	const auditFormRef = ref();

	// 表单验证规则
	const rules = reactive({
		reportNumber: [
			{ required: true, message: "请输入报告编号", trigger: "blur" },
		],
		inventoryDate: [
			{ required: true, message: "请选择盘点日期", trigger: "change" },
		],
		planId: [{ required: true, message: "请选择关联计划", trigger: "change" }],
		staff: [{ required: true, message: "请输入盘点人员", trigger: "blur" }],
		deviceProfitCount: [
			{ required: true, message: "请输入设备盘盈数", trigger: "blur" },
		],
		deviceLossCount: [
			{ required: true, message: "请输入设备盘亏数", trigger: "blur" },
		],
		materialProfitCount: [
			{ required: true, message: "请输入物料盘盈数", trigger: "blur" },
		],
		materialLossCount: [
			{ required: true, message: "请输入物料盘亏数", trigger: "blur" },
		],
	});

	const auditRules = reactive({
		auditResult: [
			{ required: true, message: "请输入审核结果", trigger: "blur" },
		],
	});

	// 获取下拉选项数据
	const fetchDropdownOptions = async () => {
		try {
			const res = await getPlanList();
			planOptions.value = res.data || [];
		} catch (error) {
			console.error("获取计划列表失败:", error);
			ElMessage.error("获取计划列表失败");
		}
	};

	// 获取盘点报告列表
	const fetchReportList = async () => {
		try {
			loading.value = true;
			const res = await listInventoryReport(queryParams);
			reportList.value = res.rows || [];
			total.value = res.total || 0;
		} catch (error) {
			console.error("获取盘点报告列表失败:", error);
			ElMessage.error("获取盘点报告列表失败");
		} finally {
			loading.value = false;
		}
	};

	// 查询按钮
	const handleQuery = () => {
		queryParams.pageNum = 1;
		fetchReportList();
	};

	// 重置查询
	const resetQuery = () => {
		queryParams.pageNum = 1;
		queryParams.reportNumber = "";
		queryParams.inventoryDate = "";
		queryParams.planId = undefined;
		queryParams.status = undefined;
		fetchReportList();
	};

	// 分页大小变化
	const handleSizeChange = (size) => {
		queryParams.pageSize = size;
		fetchReportList();
	};

	// 当前页码变化
	const handleCurrentChange = (page) => {
		queryParams.pageNum = page;
		fetchReportList();
	};

	// 表格选择变化
	const handleSelectionChange = (selection) => {
		selectedRows.value = selection;
	};

	// 新增按钮
	const handleAdd = () => {
		dialog.visible = true;
		dialog.title = "新增盘点报告";

		// 重置表单
		if (formRef.value) {
			formRef.value.resetFields();
		}

		Object.assign(form, {
			id: undefined,
			reportNumber: "",
			inventoryDate: "",
			planId: undefined,
			staff: "",
			deviceProfitCount: 0,
			deviceLossCount: 0,
			materialProfitCount: 0,
			materialLossCount: 0,
			remark: "",
		});
	};

	// 编辑按钮
	const handleEdit = async (row) => {
		try {
			const res = await getInventoryReportDetail(row.id);
			Object.assign(form, {
				id: res.data.id,
				reportNumber: res.data.reportNumber,
				inventoryDate: res.data.inventoryDate,
				planId: res.data.planId,
				staff: res.data.staff,
				deviceProfitCount: res.data.deviceProfitCount,
				deviceLossCount: res.data.deviceLossCount,
				materialProfitCount: res.data.materialProfitCount,
				materialLossCount: res.data.materialLossCount,
				remark: res.data.remark,
			});

			dialog.visible = true;
			dialog.title = "编辑盘点报告";
		} catch (error) {
			console.error("获取盘点报告详情失败:", error);
			ElMessage.error("获取盘点报告详情失败");
		}
	};

	// 查看详情
	const handleView = async (row) => {
		try {
			const res = await getInventoryReportDetail(row.id);
			detailDialog.data = res.data;
			detailDialog.visible = true;
		} catch (error) {
			console.error("获取盘点报告详情失败:", error);
			ElMessage.error("获取盘点报告详情失败");
		}
	};

	// 审核按钮
	const handleAudit = (row) => {
		auditForm.id = row.id;
		auditForm.auditResult = "";
		auditDialog.visible = true;
	};

	// 提交审核表单
	const submitAuditForm = async () => {
		try {
			await auditFormRef.value.validate();

			await auditInventoryReport(auditForm);
			ElMessage.success("审核成功");
			auditDialog.visible = false;
			fetchReportList();
		} catch (error) {
			console.error("审核盘点报告失败:", error);
		}
	};

	// 删除按钮
	const handleDelete = (row) => {
		ElMessageBox.confirm(`确认删除盘点报告 "${row.reportNumber}" 吗?`, "提示", {
			confirmButtonText: "确定",
			cancelButtonText: "取消",
			type: "warning",
		})
			.then(() => {
				return deleteInventoryReport(row.id);
			})
			.then(() => {
				ElMessage.success("删除成功");
				fetchReportList();
			})
			.catch(() => {});
	};

	// 提交表单
	const submitForm = async () => {
		try {
			await formRef.value.validate();

			if (form.id) {
				await updateInventoryReport(form);
			} else {
				await addInventoryReport(form);
			}

			ElMessage.success("操作成功");
			dialog.visible = false;
			fetchReportList();
		} catch (error) {
			console.error("保存盘点报告失败:", error);
		}
	};

	// 初始化加载数据
	onMounted(() => {
		fetchDropdownOptions();
		fetchReportList();
	});
</script>

<style scoped>
	.app-container {
		padding: 20px;
	}

	.search-card {
		margin-bottom: 20px;
	}

	.mt-1 {
		margin-top: 10px;
	}

	.mt-2 {
		margin-top: 20px;
	}

	.pre-formatted {
		white-space: pre-wrap;
		word-wrap: break-word;
		background-color: #f5f7fa;
		padding: 10px;
		border-radius: 4px;
	}
</style>
